package com.zxy.employee.controller;

import org.springframework.core.io.InputStreamResource;
import org.springframework.http.HttpHeaders;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;

import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletResponse;
import java.io.*;

@Controller
public class DownloadFileController {



    @GetMapping("/getTemplate")
    public void getTemplate(HttpServletResponse response) throws IOException {
        File file = new File("employee.xlsx");

        FileInputStream ins = new FileInputStream(file);

        response.setContentType("application/x-msdownload;charset=utf-8");
        //下载文件的名称
        response.setHeader("Content-Disposition", "attachment;filename=" + "employee.xlsx");
        ServletOutputStream sout = response.getOutputStream();
        BufferedOutputStream bos = new BufferedOutputStream(sout);

        int len;
        //10k缓冲流
        byte[] buff = new byte[1024 * 10];
        //长度保存到len,内容放入到 buff
        while (-1 != (len = (new BufferedInputStream(ins)).read(buff))) {

            bos.write(buff, 0, len);

        }

        bos.close();
        sout.close();
        ins.close();

    }

    @GetMapping("/getErrFile")
    public void getErrFile(String filename,HttpServletResponse response) throws IOException {
        File file = new File(filename);

        FileInputStream ins = null;


        if(file.exists()) {
            ins = new FileInputStream(file);
        } else {
            PrintWriter writer = response.getWriter();
            writer.write("no error");
            writer.flush();
            writer.close();
            return;
        }



        response.setContentType("text/plain;charset=utf-8");
        //下载文件的名称
        response.setHeader("Content-Disposition", "attachment;filename=" + filename);
        ServletOutputStream sout = response.getOutputStream();
        BufferedOutputStream bos = new BufferedOutputStream(sout);

        int len;
        //10k缓冲流
        byte[] buff = new byte[1024 * 10];
        //长度保存到len,内容放入到 buff
        while (-1 != (len = (new BufferedInputStream(ins)).read(buff))) {

            bos.write(buff, 0, len);

        }

        bos.close();
        sout.close();
        ins.close();
    }
}
